program tran_dbc
    use, intrinsic :: iso_fortran_env, only: real64
    implicit none
    integer :: start_int_val, end_int_val, step_int_val
    integer :: i, j, n, io_status, dof_num
    integer, allocatable :: dof_arr(:)
    character(len=10), allocatable :: dof_str(:)
    character(len=256) :: filename
    character(len=256) :: buffer
    real(real64)::val
    
    print *, "This program is used to generate FBC OR DBC file as analysis input file."

    ! 获取用户输入
    write(*, '(a)') "Input StartVal EndVal StepVal [use whitespace delimiter]       ="
    read(*, *) start_int_val, end_int_val, step_int_val
    write(*, '(a)') "Input one or more dof (1~6) [use whitespace delimiter]       ="
    read(*,  '(a)') buffer
    write(*, '(a)') 'Input number of dof                    ='
    read(*,'(I2)')  dof_num
    write(*, '(a)') 'Input value of force/displacement load ='
    read(*, '(F30.16)') val
    
    allocate(dof_arr(dof_num))
    allocate(dof_str(dof_num))
    call split_string(trim(buffer), ' ', dof_str)
    if (dof_num >1 )then
        do i=1, dof_num
            read(dof_str(i), '(I3)') dof_arr(i)
        end do
    else
        read(dof_str(1), '(I3)') dof_arr(1)
    end if
    ! 检查输入有效性
    if (step_int_val == 0) then
        write(*, '(a)') "step can not be zero!"
        stop
    end if
    
    ! 计算序列长度
    n = (end_int_val - start_int_val) / step_int_val + 1
    
    ! 生成文件名
    write(filename, '(a,i0,a,i0,a,i0,a)') "sequ_", start_int_val, "_", end_int_val, "_", step_int_val, ".csv"
    
    ! 打开文件
    open(unit=10, file=trim(filename), status='replace', action='write', iostat=io_status)
    if (io_status /= 0) then
        write(*, '(a)') "can create output file!"
        stop
    end if
    
    ! 写入CSV文件
    write(10, '(a)') "Node Index, Dof, Value"  ! 写入表头
    do j=1, dof_num
        do i = 0, n-1
            write(10, '(i15,a,i2,a,f30.16)') start_int_val + i*step_int_val,',',dof_arr(j),',',val
        end do
    end do
    ! 关闭文件
    close(10)
    
    ! 输出完成信息
    write(*, '(i0,a)') n*dof_num, " records are generated ! " 
    write(*, '(a,a)') "result has been saved in file : ", trim(filename)
    
contains
    subroutine split_string(input_str, delimiter, output_array)
        character(len=*), intent(in) :: input_str, delimiter
        character(len=*), intent(out) :: output_array(:)
        integer :: substr_num
        integer :: start_pos, end_pos

        substr_num = 0
        start_pos = 1
        do while (start_pos <= len_trim(input_str))
            end_pos = index(input_str(start_pos:), delimiter)
            if (end_pos == 0) then  ! 无剩余分隔符
                substr_num = substr_num + 1
                output_array(substr_num) = input_str(start_pos:)
                exit
            endif
            substr_num = substr_num + 1
            output_array(substr_num) = input_str(start_pos:start_pos+end_pos-2)
            start_pos = start_pos + end_pos
        end do
    end subroutine
end program tran_dbc

